package com.itfreer.gis.datasyn.sub;

import android.util.Log;

import com.itfreer.gis.GisDatabaseHelper;
import com.itfreer.gis.datasyn.entity.EditLogEntity;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.utils.config.ConfigManager;
import com.itfreer.utils.http.HttpUtils;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 编辑日志服务
 */
public class EditLogService {

    private static final String gisDataSynSN = "dataedit";

    public static final EditLogService instance = new EditLogService();
    private EditLogService() {
    }

    /**
     * 新增添加日志
     * @param config
     * @param uid
     * @return
     */
    public EditLogEntity addLog(ProjectEntity config, String uid) {
        // 记录日志
        EditLogEntity log = new EditLogEntity();
        log.setId(UUID.randomUUID().toString().replace("-",""));
        log.setDataName(config.getId());
        log.setDataID(uid);
        log.setEditType("00");
        log.setEditUserID("");
        log.setEditUserName("");
        log.setEidtDate(new Date());
        add(log);
        return log;
    }

    /**
     * 新增编辑日志
     * @param config
     * @param uid
     * @return
     */
    public EditLogEntity editLog(ProjectEntity config, String uid) {
        EditLogEntity log = new EditLogEntity();
        log.setDataID(uid);
        log.setEditType("01");

        // 查询，如果记录编辑过了，就不在记录
        try {
            Dao<EditLogEntity, String> dao = GisDatabaseHelper.getInstance().getDao(EditLogEntity.class);
            List<EditLogEntity> list = dao.queryForMatching(log);
            if(list!=null && list.size()>0){
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 记录日志
        log.setId(UUID.randomUUID().toString().replace("-",""));
        log.setDataName(config.getId());
        log.setEditUserID("");
        log.setEditUserName("");
        log.setEidtDate(new Date());
        add(log);
        return log;
    }

    /**
     * 新增删除日志
     * @param config
     * @param uid
     * @return
     */
    public EditLogEntity deleteLog(ProjectEntity config, String uid) {
        // 记录日志
        EditLogEntity log = new EditLogEntity();
        log.setId(UUID.randomUUID().toString().replace("-",""));
        log.setDataName(config.getId());
        log.setDataID(uid);
        log.setEditType("02");
        log.setEditUserID("");
        log.setEditUserName("");
        log.setEidtDate(new Date());
        add(log);
        return log;
    }

    /**
     * 添加日志
     * @param entity
     * @return
     */
    public EditLogEntity add(final EditLogEntity entity) {
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GisDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<EditLogEntity> callable  = new Callable<EditLogEntity>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public EditLogEntity call() throws Exception {
                // 先在本地创建一个日志
                Dao<EditLogEntity, String> dao = GisDatabaseHelper.getInstance().getDao(EditLogEntity.class);
                dao.create(entity);
                return entity;
            }
        };

        try {
            //执行事件
            return transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存上传同步工程
     *
     * @param synID
     * @return
     */
    public Boolean uploadLog(String synID) {
        final String url = ConfigManager.getConfig("HttpUrl").toString() + "/rest/" + gisDataSynSN + "/uploadLog/" + synID;
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GisDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<Boolean> callable  = new Callable<Boolean>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public Boolean call() throws Exception {
                Dao<EditLogEntity, String> dao = GisDatabaseHelper.getInstance().getDao(EditLogEntity.class);
                List<EditLogEntity> logs = dao.queryForAll();
                return HttpUtils.post(url, logs, Boolean.class);
            }
        };

        Boolean result;
        try {
            //执行事件
            result =  transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            result = false;
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 数据同步后，删除日志
     * @return
     */
    public Boolean clearLogs(){
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GisDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<Boolean> callable  = new Callable<Boolean>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public Boolean call() throws Exception {
                Dao<EditLogEntity, String> dao = GisDatabaseHelper.getInstance().getDao(EditLogEntity.class);
                // 清空表
                dao.queryRaw("delete from edit_log");
                return true;
            }
        };

        Boolean result;
        try {
            //执行事件
            result =  transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            result = false;
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
        }
        return result;
    }
}
